package com.sneakxy.jdbc;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.sneakxy.config.Jdbc;

/**
 * Mysql方言
 * @author 潜行的青衣
 * @see
 */
public class MysqlDialect implements Dialect {

	private String database;
	
	/* (non-Javadoc)
	 * @see com.sneakxy.mybase4j.generator.jdbc.Dialect#getTablesSql()
	 */
	@Override
	public String getTablesSql() {
		return StringUtils.join("select table_name from information_schema.tables where table_schema='", database, "' and table_type='base table'");
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybase4j.generator.jdbc.Dialect#setUrl(java.lang.String)
	 */
	@Override
	public void setUrl(String url) {
		int index = StringUtils.lastIndexOf(url, "/");
		int lastIndex = StringUtils.indexOf(url, "?");
		if(lastIndex > -1) {
			this.database = StringUtils.substring(url, index + 1, lastIndex);
		} else {
			this.database = StringUtils.substring(url, index + 1);
		}
	}

	public String getDatabase() {
		return database;
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybase4j.generator.jdbc.Dialect#getSelectNone(java.lang.String)
	 */
	@Override
	public String getSelectNone(String table) {
		return StringUtils.join("select * from ", table, " where 1!=1");
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybase4j.generator.jdbc.Dialect#getCatalog()
	 */
	@Override
	public String getCatalog(Jdbc jdbc, String tableName) {
		return getSchema(jdbc, tableName);
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybase4j.generator.jdbc.Dialect#getSchema()
	 */
	@Override
	public String getSchema(Jdbc jdbc, String tableName) {
		if(StringUtils.contains(tableName, ".")) {
			return StringUtils.split(tableName, ".")[0];
		}
		return getDatabase();
	}

	@Override
	public String getCreateSql(String tableName, String sql, String charset) {
		//ENGINE = MERGE UNION = (`user1`,`user2`,`user3`);
		return StringUtils.join("CREATE TABLE ", tableName, sql, " ENGINE = MyISAM DEFAULT CHARSET=", charset, ";");
	}

	@Override
	public String getCreateUnionSql(List<String> union, String tableName, String sql, String charset) {
		String unions = StringUtils.join("(", StringUtils.join(union, ","), ")");
		return StringUtils.join("CREATE TABLE ", tableName, sql, " ENGINE = MERGE UNION = ", unions, " CHARSET=", charset, ";");
	}

	@Override
	public String[] getAlterTableSql(List<String> union, String tableName, String alterSql, String createSql, String charset) {
		
		return new String[] {
				StringUtils.join("DROP TABLE ", tableName, ";"),
				getCreateUnionSql(union, tableName, createSql, charset)
		};
	}
	
}
